package cn.edu.sdjzu;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.util.ArrayList;
import java.util.List;
@SpringBootApplication
public class SentinelApplication {
    public static void main(String[] args) {
        // 启动Spring应用
        SpringApplication.run(SentinelApplication.class, args);

        // 初始化限流规则
        initFlowRules();

        while (true) {
            try (Entry entry = SphU.entry("HelloWorld")) {
                System.out.println("hello world, sentinel9031");
            } catch (BlockException ex) {
                System.out.println("Sentinel9031 is blocked!");
            }
            try {
                Thread.sleep(375); // 增加延迟，避免CPU占用过高
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

    private static void initFlowRules() {
        List<FlowRule> rules = new ArrayList<>();
        FlowRule rule = new FlowRule();
        rule.setResource("HelloWorld"); // 设置资源名称
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS); // 设置限流类型为QPS
        rule.setCount(2); // 设置限流阈值为2次/秒
        rules.add(rule);
        FlowRuleManager.loadRules(rules); // 加载规则
    }
}
